package com.powernode.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powernode.domain.Member;
import com.powernode.model.Result;
import com.powernode.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 管理系统：会员业务控制层
 */
@Api(tags = "管理系统会员接口管理")
@RequestMapping("admin/user")
@RestController
public class SysMemberController {

    @Autowired
    private MemberService memberService;

    /**
     * 多条件分页查询会员
     *
     * @param current  页码
     * @param size     每页显示条件
     * @param nickName 会员昵称
     * @param status   会员状态
     * @return
     */

    @ApiOperation("多条件分页查询会员")
    @GetMapping("page")
    @PreAuthorize("hasAuthority('admin:user:page')")
    public Result<Page<Member>> loadMemberPage(Long current, Long size, @RequestParam(required = false) String nickName, @RequestParam(required = false) Integer status) {
        Page<Member> page = new Page<>(current, size);
        page = memberService.page(page, new LambdaQueryWrapper<Member>().eq(ObjectUtil.isNotNull(status), Member::getStatus, status).like(StringUtils.hasText(nickName), Member::getNickName, nickName).orderByDesc(Member::getCreateTime));
        return Result.success(page);
    }

    /**
     * 根据标识查询会员信息
     *
     * @param id 会员id
     * @return
     */
    @ApiOperation("根据标识查询会员信息")
    @GetMapping("info/{id}")
    @PreAuthorize("hasAuthority('admin:user:info')")
    public Result<Member> loadMemberInfo(@PathVariable Long id) {
        // 查询会员信息，仅选择id、openId、pic和nickName字段
        Member member = memberService.getOne(new LambdaQueryWrapper<Member>().select(Member::getId, Member::getOpenId, Member::getPic, Member::getNickName, Member::getStatus).eq(Member::getId, id));
        // 返回查询结果
        return Result.success(member);
    }

    /**
     * 修改会员状态
     *
     * @param member 会员对象（id,status）
     * @return
     */
    @ApiOperation("修改会员状态")
    @PutMapping
    @PreAuthorize("hasAuthority('admin:user:update')")
    public Result modifyMemberStatus(@RequestBody Member member) {
        member.setUpdateTime(new Date());
        Boolean updated = memberService.updateById(member);
        return Result.handle(updated);
    }

    /**
     * 批量删除会员
     *
     * @param ids 会员id集合
     * @return
     */
    @ApiOperation("批量删除会员")
    @DeleteMapping
    @PreAuthorize("hasAuthority('admin:user:delete')")
    public Result<String> removeMembers(@RequestBody List<Long> ids) {
        // 根据传入的会员ID列表创建一个会员对象列表，用于批量更新会员状态
        List<Member> memberList = new ArrayList<>();
        // 遍历每个会员ID，创建一个会员对象并设置其ID和状态为-1（表示删除），然后添加到会员列表中
        ids.forEach(id -> {
            Member member = new Member();
            member.setId(id);
            member.setStatus(-1);
            memberList.add(member);
        });
        // 调用会员服务的批量更新方法，根据会员ID列表更新会员状态
        Boolean removed = memberService.updateBatchById(memberList);
        // 根据更新结果返回操作结果
        return Result.handle(removed);
    }
////////////////////// feign 接口 /////////////////////////////

    /**
     * 根据OpenId获取用户的昵称
     *
     * @param openId 用户的OpenId，用于唯一标识用户
     * @return 返回一个Result对象，其中包含用户的昵称
     */
    @GetMapping("getNickNameByOpenId")
    Result<String> getNickNameByOpenId(@RequestParam String openId) {
        // 通过OpenId查询用户昵称
        Member member = memberService.getOne(new LambdaQueryWrapper<Member>().select(Member::getNickName).eq(Member::getOpenId, openId));
        // 返回查询到的用户昵称
        return Result.success(member.getNickName());
    }
}